/*
 * @Author: 孙大大
 * @Date: 2022-04-13 18:42:37
 * @LastEditTime: 2022-04-13 18:42:38
 * @FilePath: \hmmm-xdy\src\store\modules\user.js
 */
/*
 * @Author: 孙大大
 * @Date: 2022-04-09 02:34:21
 * @LastEditTime: 2022-04-09 09:07:55
 * @FilePath: \黑马面面\src\store\modules\user.js
 */
import { getToken, setToken, removeToken } from "@/utils/auth";
import { login, getUserInfo, getUserDetailById } from "@/api/user";
import { resetRouter } from "@/router";
const state = {
  // TODO: 实际情况修改
  token: getToken(),
  userInfo: {},
};
const mutations = {
  // TODO: 实际情况修改
  setToken(state, token) {
    state.token = token;
    setToken(token);
  },
  removeToken(state) {
    state.token = null;
    removeToken();
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo;
    console.log(userInfo);
  },
  removeUserInfo(state) {
    state.userInfo = {};
  },
};
const actions = {
  // TODO: 实际情况修改
  async login(context, data) {
    const token = await login(data);
    console.log(token.token);
    context.commit("setToken", token.token);
  },
  async getUserInfo(context) {
    const userInfo = await getUserInfo();
    // console.log(userInfo);
    // const result = await getUserDetailById(info.userId)

    // const userInfo = { ...info, ...result }

    context.commit("setUserInfo", userInfo);
    // console.log(state.userInfo);
    return userInfo; // 返回用户资料
  },
  logout(context) {
    context.commit("removeToken");
    context.commit("removeUserInfo");
    // 1. 退出的时候，要重置路由实例
    resetRouter();
    console.log(444444);
    // 2. 清除 permissions 模块里面state里面的routes
    // 需求：如何在A模块的action里面 调用 B模块的 mutations或者action
    // context.commit('setRoutes',[])
    // 错误的！ 这样写是调用当前模块的setRoutes
    // context.commit('permission/setRoutes',[])
    // 错误的！ 这样写是调用当前模块的的子模块permission模块里的mutations里的setRoutes
    context.commit("permission/setRoutes", [], { root: true });
    // 传入第三个参数，配置项，表示从根模块开始去查找调用
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
